import operate from '@dfeidao/atom-nodejs/db/operate';
import call_service from '@dfeidao/atom-nodejs/msg/call-service';

interface Message {
	usercode: string;
	password: string;
	user_name: string;
	name_spell: string;
	is_disabled: boolean;
	create_time: number;
	email: string;
	phone: string;
	avatar_path: string;
	avatar_name: string;
	avatar_type: string;
	productid: string;
	last_login_time: number;
	phone_verified: boolean;
	email_verified: boolean;
	is_admin: boolean;
}

export default async function atom(msg: Message, action_id: string, session_id: string, spaceid: string) {
	const { exec, insert, del } = operate(action_id, session_id, '12');
	insert('pub_user', {
		usercode: msg.usercode,
		password: msg.password,
		user_name: msg.user_name,
		name_spell: msg.name_spell,
		is_disabled: msg.is_disabled,
		create_time: msg.create_time,
		email: msg.email,
		phone: msg.phone,
		avatar_path: msg.avatar_path,
		avatar_name: msg.avatar_name,
		avatar_type: msg.avatar_type,
		productid: msg.productid,
		last_login_time: msg.last_login_time,
		phone_verified: msg.phone_verified,
		email_verified: msg.email_verified,
		is_admin: msg.is_admin
	});
	const res = await exec();
	if (res.code === 1) {
		let error = '';
		try {
			const res1 = await call_service<{ code: number; msg: string; }>(action_id, session_id, 'busiservice.kinthoa.register', {
				systemid: "7381",
				spaceid: "kinth_oa",
				productid: "kinth_oa",
				usercode: msg.usercode
			});
			if (!res1.code) {
				error = res1.msg;
			}
		} catch (err) {
			error = err.message;
		}
		if (error) {
			del('pub_user', {
				usercode: msg.usercode,
				password: msg.password,
				user_name: msg.user_name,
				name_spell: msg.name_spell,
				is_disabled: msg.is_disabled,
				create_time: msg.create_time,
				email: msg.email,
				phone: msg.phone,
				avatar_path: msg.avatar_path,
				avatar_name: msg.avatar_name,
				avatar_type: msg.avatar_type,
				productid: msg.productid,
				last_login_time: msg.last_login_time,
				phone_verified: msg.phone_verified,
				email_verified: msg.email_verified,
				is_admin: msg.is_admin
			});
			await exec();
			return { code: 0, msg: '保存失败', error };
		} else {
			return { code: 1, msg: '保存成功' };
		}
	} else {
		return { code: 0, msg: '保存失败' };
	}
}
